<template>
  <el-dialog
    v-model="dialog.visible"
    :title="dialogTitle"
    @open="openHandler"
    @close="closeHandler"
    :close-on-click-modal="false"
    append-to-body
    center
    width="60%"
  >
    <el-form
      ref="dataForm"
      :rules="formRules"
      :model="entity"
      :disabled="operation == 3"
      label-suffix="："
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="clientId" label="应用ID">
            <el-input
              v-model="entity.clientId"
              placeholder="请输入应用ID"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="clientName" label="应用名称">
            <el-input
              v-model="entity.clientName"
              placeholder="请输入应用名称"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="authorizationGrantTypes" label="授权类型">
            <el-checkbox-group v-model="entity.authorizationGrantTypes">
              <el-checkbox
                value="authorization_code"
                label="authorization_code"
              />
              <el-checkbox
                value="client_credentials"
                label="client_credentials"
              />
              <el-checkbox value="refresh_token" label="refresh_token" />
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="clientAuthenticationMethods" label="认证方式">
            <el-checkbox-group v-model="entity.clientAuthenticationMethods">
              <el-checkbox value="basic" label="basic" />
              <el-checkbox
                value="client_secret_basic"
                label="client_secret_basic"
              />
              <el-checkbox
                value="client_secret_post"
                label="client_secret_post"
              />
              <el-checkbox
                value="client_secret_jwt"
                label="client_secret_jwt"
              />
              <el-checkbox value="private_key_jwt" label="private_key_jwt" />
              <el-checkbox value="none" label="none" />
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="scopes" label="授权范围">
            <div style="display: flex; flex-direction: column">
              <template
                v-for="server in resourceServers"
                :key="server.serverId"
              >
                <div v-if="server.scopes != null && server.scopes.length > 0">
                  <span style="font-weight: bold">{{ server.serverName }}</span>
                  <el-checkbox-group v-model="entity.scopes">
                    <el-checkbox
                      v-for="scope in server.scopes"
                      :key="scope"
                      :value="scope"
                      :label="scope"
                    />
                  </el-checkbox-group>
                </div>
              </template>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="redirectUris" label="重定向URI">
            <el-select
              v-model="entity.redirectUris"
              multiple
              allow-create
              filterable
              placeholder="请输入重定向URI"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="过期时长设置"> 单位均为分钟 </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="authorizationCodeTimeToLive" label="授权码">
            <el-input-number
              v-model="entity.authorizationCodeTimeToLive"
              :min="1"
              :max="60"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="accessTokenTimeToLive" label="accessToken">
            <el-input-number
              v-model="entity.accessTokenTimeToLive"
              :min="1"
              :max="10080"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="refreshTokenTimeToLive" label="refreshToken">
            <el-input-number
              v-model="entity.refreshTokenTimeToLive"
              :min="1"
              :max="302400"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item
            prop="requireAuthorizationConsent"
            label="是否询问用户授权"
          >
            <el-switch v-model="entity.requireAuthorizationConsent" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="requireProofKey" label="是否开启PKCE">
            <el-switch v-model="entity.requireProofKey" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="enable" label="是否启用">
            <el-switch v-model="entity.enable" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <cancel-button @click="dialog.visible = false" />
      <save-button
        v-if="operation != 3"
        :loading="loading"
        @click="saveHandler"
      />
    </template>
  </el-dialog>
</template>
<script>
import { fetchList as fetchResourceServerList } from '@/api/upms/resourceServer'
import { save, update } from '@/api/upms/oauth2Client'

export default {
  name: 'Oauth2ClientEdit',
  props: {
    dialog: {
      type: Object,
      required: true,
    },
  },
  emits: ['success'],
  data() {
    return {
      loading: false,
      entity: {},
      titleMap: {
        1: '新建OAuth2应用',
        2: '编辑OAuth2应用',
        3: '查看OAuth2应用',
      },
      formRules: {
        clientId: [
          { required: true, message: '请输入应用ID', trigger: 'blur' },
        ],
        clientName: [
          { required: true, message: '请输入应用名称', trigger: 'blur' },
        ],
        authorizationGrantTypes: [
          { required: true, message: '请选择授权类型', trigger: 'blur' },
        ],
        clientAuthenticationMethods: [
          { required: true, message: '请输入认证方式', trigger: 'blur' },
        ],
        scopes: [
          { required: true, message: '请选择授权范围', trigger: 'blur' },
        ],
        authorizationCodeTimeToLive: [
          {
            required: true,
            message: '请输入授权码',
            trigger: 'blur',
          },
        ],
        accessTokenTimeToLive: [
          {
            required: true,
            message: '请输入accessToken',
            trigger: 'blur',
          },
        ],
        refreshTokenTimeToLive: [
          {
            required: true,
            message: '请输入refreshToken',
            trigger: 'blur',
          },
        ],
      },
      oidcScopes: ['openid', 'profile', 'email', 'address', 'phone'],
      resourceServers: [],
    }
  },
  computed: {
    operation() {
      return this.dialog.operation
    },
    dialogTitle() {
      return this.titleMap[this.dialog.operation]
    },
  },
  methods: {
    openHandler() {
      let entity = Object.assign(
        {
          authorizationCodeTimeToLive: 5,
          accessTokenTimeToLive: 120,
          refreshTokenTimeToLive: 10080,
          requireAuthorizationConsent: true,
          requireProofKey: false,
          menuRelated: false,
          enable: true,
        },
        this.dialog.entity
      )

      if (entity.authorizationGrantTypes) {
        entity.authorizationGrantTypes =
          entity.authorizationGrantTypes.split(',')
      } else {
        entity.authorizationGrantTypes = []
      }
      if (entity.clientAuthenticationMethods) {
        entity.clientAuthenticationMethods =
          entity.clientAuthenticationMethods.split(',')
      } else {
        entity.clientAuthenticationMethods = []
      }

      if (entity.redirectUris) {
        entity.redirectUris = entity.redirectUris.split(',')
      } else {
        entity.redirectUris = []
      }
      if (entity.scopes) {
        entity.scopes = entity.scopes.split(',')
      } else {
        entity.scopes = []
      }

      this.entity = entity

      fetchResourceServerList().then((res) => {
        let data = res.data.data
        for (let i in data) {
          data[i].scopes.sort()
        }

        this.resourceServers = data
      })

      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    closeHandler() {
      this.entity = {
        authorizationGrantTypes: [],
        clientAuthenticationMethods: [],
        redirectUris: [],
        scopes: [],
      }
      this.$refs.dataForm.clearValidate()
    },
    saveHandler() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.loading = true
          let edit = this.operation == 1 ? save : update
          edit(this.entity)
            .then((res) => {
              this.dialog.visible = false
              this.$message.success('保存成功')

              if (this.operation == 1) {
                this.$alert(
                  '请牢记密钥，丢失无法找回：' + res.data.data,
                  'Title',
                  {
                    confirmButtonText: '记住了',
                    callback: () => {
                      this.$emit('success')
                    },
                  }
                )
              } else {
                this.$emit('success')
              }
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
  },
}
</script>
